var express = require('express');
var router = express.Router();
var smartUtil = require('./ccServer');
var MongoDB = require('../../database/mongodb');

router.post('/loginByToken', function(req, res, next) {
  smartUtil.getContextByToken(req.body.accessToken).then((email) => {
    let conditions = {
      email: email
    }
    MongoDB.findOne('users', conditions, (err, docs) => {
      if (err) {
        next(new Error('单点登录失败，找不到用户'))
      } else {
        res.cookie("user", docs, { maxAge: 1000 * 60 * 30 });
        res.json(docs);
      }
    });
  }).catch((code) => {
    next(new Error('单点登录失败，请输入账号密码登录'))
  })
});

router.post('/login', function(req, res, next) {
  ewLogin(req, res, next).then((data) => {
    res.cookie("user", data, { maxAge: 1000 * 60 * 30 });
    saveOrUpdateUser(data, req)
    res.json(data);
  }).catch((code) => {
    if (code == 0) {
      next(new Error('用户已停用'))
    } else {
      ccLogin(req).then((ccUser) => {
        newUserLogin(ccUser, req, res, next)
      }).catch((err) => {
        console.log('error:' + err)
        next(err);
      });
    }
  })
});

/**
 * 获取用户有权限的菜单.
 */
router.get('/getMenuList', function(req, res, next) {
  let loginUser = req.cookies['user']
  let condition = {
    roleId: { '$in': loginUser.roleIds }
  }
  MongoDB.find('roleMenus', condition, null, null, function (err, docs) {
    if (err) {
      res.status(500).send("查询失败");
    } else {
      let menuIds = new Set()
      for (let index = 0; index < docs.length; index++) {
        const element = docs[index];
        menuIds.add(element.menuId)
      }
      let condition = {
        id: { '$in': [...menuIds] }
      }
      MongoDB.find('menus', condition, null, { sort: 1 }, function (err, menuList) {
        if (err) {
          res.status(500).send("查询失败");
        } else {
          res.json(menuList);
        }
      });
    }
  });
})

function newUserLogin(ccUser, req, res, next) {
  let conditions = {
    email: ccUser.loginName
  }
  MongoDB.findOne('users', conditions, (err, docs) => {
    if(!err && docs){
      res.cookie("user", docs, { maxAge: 1000 * 60 * 30 });
      docs.password = getParamter(req, 'password')
      saveOrUpdateUser(docs, req)
      res.json(docs);
    } else {
      let newUser = {
        userName: ccUser.userName,
        password: getParamter(req, 'password'),
        email: ccUser.loginName,
        sex: ccUser.sex,
        state: 1,
        orgId: [2],
        roleIds: [15, 19]
      }
      console.log('保存新用户')
      saveOrUpdateUser(newUser, req).then(data => {
        res.cookie("user", data, { maxAge: 1000 * 60 * 30 });
        res.json(data)
      })
    }
  });
}

router.get('/logout', function(req, res, next){
  res.clearCookie("user");
  res.sendStatus(200);
});

router.get('/ping', (req, res) => {
  res.status(200).send("pong!");
});

/**
 * 当前系统登录.
 */
function ewLogin(req, res, next){
  console.log('ewlogin');
  let userName = getParamter(req, 'userName');
  let password = getParamter(req, 'password');
  let conditions = {
    '$or': [
      { loginName: userName },
      { email: userName }
    ]
  }
  return new Promise((resolve, reject) => {
    MongoDB.findOne('users', conditions, (err, docs) => {
      if(!err && docs){
        if (docs.state === 0) {
          reject(0)
        }
        if(docs.password === password){
          resolve(docs);
        } else {
          reject(docs);
        }
      } else {
        reject(1);
      }
    });
  });
}

function ccLogin(req){
  console.log('cclogin');
  return new Promise((resolve, reject) => {
    smartUtil.login(req.body).then((res) => {
      if (res.data.code === 0) {
        resolve(res.data.body);
      } else {
        reject(new Error(res.data.message))
      }
    }).catch((err) => {
      console.log('cclogin' + err)
      reject(err)
    })
  });
}

/**
 * 保存用户
 */
function saveOrUpdateUser(user, req) {
  let condition = {
    email: user.email
  }
  return new Promise((resolve, reject) => {
    MongoDB.updateData('users', condition, user, (err, docs) => {
      if(!err){
        MongoDB.findOne('users', condition, (err, data) => {
          resolve(data);
        })
      } else {
        reject(err);
      }
    });
  });
}

/**
 * @getClientIP
 * @desc 获取用户 ip 地址
 * @param {Object} req - 请求
 */
function getClientIP(req) {
  return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
      req.connection.remoteAddress || // 判断 connection 的远程 IP
      req.socket.remoteAddress || // 判断后端的 socket 的 IP
      req.connection.socket.remoteAddress;
};

function getParamter(req, key) {
  let params = req.body;
  return params[key]
}

module.exports = router;
